/*
 * @Author: 白川 杏 baiyufeisteam@163.com
 * @Date: 2023-05-24 14:28:11
 * @LastEditors: 白川 杏 baiyufeisteam@163.com
 * @LastEditTime: 2023-06-12 15:52:32
 * @FilePath: \herb-garden\backend\koaserver\routes\growtime.js
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
const router = require('koa-router')()
const fs = require("fs");
const path = require("path");
const uploadDir = path.join(__dirname, '../images/growtime');

router.prefix('/growtime')
//backend growtime 植物生长阶段所需时间

//页面初始化时获取数据库内的数据条目
router.post('/getgrowtime', async (ctx, next) => {
    let resultcropsid = await ctx.db.EXCUTE("SELECT (SELECT cropname FROM tags ni WHERE n.cropsid=ni.cropsid) AS cropinfo FROM growtime n")
    //获取所有的cropname和potname
    let resultcropall = await ctx.db.EXCUTE("SELECT cropname AS cropall FROM tags")
    let resultpotall = await ctx.db.EXCUTE("SELECT potname AS potall FROM flowerpot")
    let result = await ctx.db.EXCUTE("SELECT n.*, (SELECT potname FROM flowerpot ni WHERE n.potid=ni.potid) AS potinfo FROM growtime n")

    for (let i = 0; i < result.length; i++) {
        Object.assign(result[i], resultcropsid[i]);
        Object.assign(result[i], resultcropall[i]);
        Object.assign(result[i], resultpotall[i]);
    }

    ctx.body = {
        code: 200,
        data: result
    };
})

function filterArr(arr1, arr2) {
    var uid1 = []
    var uid2 = []
    for (var i in arr1) {
        uid1.push('http://localhost:8080' + arr1[i].growimg)
    }
    for (var i in arr2) {
        uid2.push(arr2[i].url)
    }
    const arr = [...uid1, ...uid2];
    const newArr = arr.filter(item => {
        console.log();
        if (uid2.includes(item)) {
            console.log(1);
            return false
        } else {
            console.log(2, item);
            return true
        }
    });

    return newArr;
}

//backend 增加项
router.post('/addgrowtimebackend', async (ctx, next) => {
    let stage1grownum = ctx.request.body.stage1grownum;
    let stage2grownum = ctx.request.body.stage2grownum;
    let stage3grownum = ctx.request.body.stage3grownum;
    let stage4grownum = ctx.request.body.stage4grownum;

    let stage1growday = ctx.request.body.stage1growday;
    let stage2growday = ctx.request.body.stage2growday;
    let stage3growday = ctx.request.body.stage3growday;
    let stage4growday = ctx.request.body.stage4growday;

    let stage1growimg = ctx.request.body.stage1growimg;
    let stage2growimg = ctx.request.body.stage2growimg;
    let stage3growimg = ctx.request.body.stage3growimg;
    let stage4growimg = ctx.request.body.stage4growimg;

    let stage1waterday = ctx.request.body.stage1waterday;
    let stage2waterday = ctx.request.body.stage2waterday;
    let stage3waterday = ctx.request.body.stage3waterday;
    let stage4waterday = ctx.request.body.stage4waterday;

    let stage1fertilize = ctx.request.body.stage1fertilize;
    let stage2fertilize = ctx.request.body.stage2fertilize;
    let stage3fertilize = ctx.request.body.stage3fertilize;
    let stage4fertilize = ctx.request.body.stage4fertilize;

    let cropinfo = ctx.request.body.cropinfo;

    //insert tags
    let sqlinsertcrops = 'INSERT INTO tags (cropname) VALUES (?)'
    let resultinsertcrops = await ctx.db.EXCUTE(sqlinsertcrops, [cropinfo]);

    //cropsid?potid?
    let sqlcropsid = 'SELECT cropsid FROM tags WHERE cropname=?'
    let resultgetcropsid = await ctx.db.EXCUTE(sqlcropsid, [cropinfo]);
    console.log(resultgetcropsid[0].cropsid);

    var base64Data = stage1growimg[0].url.replace(/^data:image\/\w+;base64,/, "");
    var dataBuffer = Buffer.from(base64Data, 'base64');
    let imgUrl = uploadDir + '\\' + stage1growimg[0].name
    fs.writeFileSync(imgUrl, dataBuffer)

    var base64Data = stage2growimg[0].url.replace(/^data:image\/\w+;base64,/, "");
    var dataBuffer = Buffer.from(base64Data, 'base64');
    let imgUrlstage2growimg = uploadDir + '\\' + stage2growimg[0].name
    fs.writeFileSync(imgUrlstage2growimg, dataBuffer)

    var base64Data = stage3growimg[0].url.replace(/^data:image\/\w+;base64,/, "");
    var dataBuffer = Buffer.from(base64Data, 'base64');
    let imgUrlstage3growimg = uploadDir + '\\' + stage3growimg[0].name
    fs.writeFileSync(imgUrlstage3growimg, dataBuffer)

    var base64Data = stage4growimg[0].url.replace(/^data:image\/\w+;base64,/, "");
    var dataBuffer = Buffer.from(base64Data, 'base64');
    let imgUrlstage4growimg = uploadDir + '\\' + stage4growimg[0].name
    fs.writeFileSync(imgUrlstage4growimg, dataBuffer)

    let sqlstage1 = 'INSERT INTO growtime (grownum,growday,cropsid,growimg,waterday,fertilize) VALUES (?,?,?,?,?,?)'
    await ctx.db.EXCUTE(sqlstage1, [stage1grownum, stage1growday, resultgetcropsid[0].cropsid, '/images/growtime/' + stage1growimg[0].name, stage1waterday, stage1fertilize]);

    let sqlstage2 = 'INSERT INTO growtime (grownum,growday,cropsid,growimg,waterday,fertilize) VALUES (?,?,?,?,?,?)'
    await ctx.db.EXCUTE(sqlstage2, [stage2grownum, stage2growday, resultgetcropsid[0].cropsid, '/images/growtime/' + stage2growimg[0].name, stage2waterday, stage2fertilize]);

    let sqlstage3 = 'INSERT INTO growtime (grownum,growday,cropsid,growimg,waterday,fertilize) VALUES (?,?,?,?,?,?)'
    await ctx.db.EXCUTE(sqlstage3, [stage3grownum, stage3growday, resultgetcropsid[0].cropsid, '/images/growtime/' + stage3growimg[0].name, stage3waterday, stage3fertilize]);

    let sqlstage4 = 'INSERT INTO growtime (grownum,growday,cropsid,growimg,waterday,fertilize) VALUES (?,?,?,?,?,?)'
    await ctx.db.EXCUTE(sqlstage4, [stage4grownum, stage4growday, resultgetcropsid[0].cropsid, '/images/growtime/' + stage4growimg[0].name, stage4waterday, stage4fertilize]);

    let resultcropsid = await ctx.db.EXCUTE("SELECT (SELECT cropname FROM tags ni WHERE n.cropsid=ni.cropsid) AS cropinfo FROM growtime n")
    //获取所有的cropname和potname
    let resultcropall = await ctx.db.EXCUTE("SELECT cropname AS cropall FROM tags")
    let result = await ctx.db.EXCUTE("SELECT n.*, (SELECT potname FROM flowerpot ni WHERE n.potid=ni.potid) AS potinfo FROM growtime n")

    for (let i = 0; i < result.length; i++) {
        Object.assign(result[i], resultcropsid[i]);
        Object.assign(result[i], resultcropall[i]);
    }

    ctx.body = {
        code: 200,
        data: result
    }

});

//删除项
router.post('/delgrowtimebackend', async (ctx, next) => {
    let grow = ctx.request.body.growid;
    console.log(grow);
    for (let i = 0; i < grow.length; i++) {
        fs.unlink(path.join(__dirname, '../' + grow[i].growimg), async function (err) {
            if (err) {
                console.log(err);
                ctx.body = {
                    code: 400
                }
            }
            let sqldelbygrowid = 'DELETE FROM growtime WHERE growid=?'
            await ctx.db.EXCUTE(sqldelbygrowid, [grow[i].growid]);
            ctx.body = {
                code: 200,
                // data: result1
            }
        })

    }
    let resultcropsid = await ctx.db.EXCUTE("SELECT (SELECT cropname FROM tags ni WHERE n.cropsid=ni.cropsid) AS cropinfo FROM growtime n")
    //获取所有的cropname和potname
    let resultcropall = await ctx.db.EXCUTE("SELECT cropname AS cropall FROM tags")
    let result = await ctx.db.EXCUTE("SELECT n.*, (SELECT potname FROM flowerpot ni WHERE n.potid=ni.potid) AS potinfo FROM growtime n")

    for (let i = 0; i < result.length; i++) {
        Object.assign(result[i], resultcropsid[i]);
        Object.assign(result[i], resultcropall[i]);
    }

    ctx.body = {
        code: 200,
        data: result
    };
})

//编辑 上传图片
router.post('/modifyuploadimggrowtimebackend', async (ctx, next) => {
    let growid = ctx.request.body.growid;
    let grownum = ctx.request.body.grownum;
    let growday = ctx.request.body.growday;
    let waterday = ctx.request.body.waterday;
    let fertilize = ctx.request.body.fertilize;
    let cropinfo = ctx.request.body.cropinfo;
    let potinfo = ctx.request.body.potinfo;
    let growimg = ctx.request.body.growimg;
    console.log('growimg');
    console.log(growimg);

    //get cropsid
    //get potid
    let sqlcropsid = 'SELECT cropsid FROM tags WHERE cropname=?'
    let resultgetcropsid = await ctx.db.EXCUTE(sqlcropsid, [cropinfo]);
    console.log(resultgetcropsid[0].cropsid);

    let growimglist = await ctx.db.EXCUTE("select growimg from growtime where growid=?", [growid]);
    console.log(growimglist[0].growimg);
    if (growimglist[0].growimg == growimg) {
        for (let i = 0; i < growimg.length; i++) {
            let m = growimg[i].replace('/http://localhost:8080/', '')
            let n = growimg[i].split('http://localhost:8080/')[1]
            console.log(m);
            console.log(n);
            fs.unlink(path.join(__dirname, '../' + n), async function (err) {
                if (err) {
                    console.log(err);
                    ctx.body = {
                        code: 400
                    }
                }
                await ctx.db.EXCUTE("update growtime set growimg='' where growid=?", [growid]);
            })
        }
    }

    for (let i = 0; i < ctx.request.body.growimg.length; i++) {
        console.log('growimg[i]');
        console.log(growimg[i])
        if (!growimg[i].url.includes("http://localhost:8080")) {
            var base64Data = growimg[i].url.replace(/^data:image\/\w+;base64,/, "");
            var dataBuffer = Buffer.from(base64Data, 'base64');
            let imgUrl = uploadDir + '\\' + growimg[i].name
            fs.writeFileSync(imgUrl, dataBuffer)
            //let sql1 = 'INSERT INTO growtime (grownum,growday,cropsid,growimg,potid,waterday,fertilize) VALUES (?,?,?,?,?,?,?)'

            if (i == 0) {
                // console.log(0);
                console.log(growid);
                console.log('/images/growtime/' + growimg[i].name);
            }
            let sql = 'UPDATE growtime SET grownum=?, growday=?, cropsid=?, growimg=?, waterday=?, fertilize=? WHERE growid=?'
            await ctx.db.EXCUTE(sql, [grownum, growday, resultgetcropsid[0].cropsid, '/images/growtime/' + growimg[i].name, waterday, fertilize, growid]);
            //await ctx.db.EXCUTE(sql1, [grownum, growday, resultgetcropsid[0].cropsid, '/images/growtime/' + growimg[i].name, resultpotid[0].potid, waterday, fertilize]);
        } else {
            if (i == 0) {
                //console.log(112);
                console.log(growimg[0]);
                let n = growimg[i].url.split('http://localhost:8080')[1]
                console.log(n);
                let sql = 'UPDATE growtime SET grownum=?, growday=?, cropsid=?, growimg=?, waterday=?, fertilize=? WHERE growid=?'
                await ctx.db.EXCUTE(sql, [grownum, growday, resultgetcropsid[0].cropsid, n, waterday, fertilize, growid]);
            }
        }
    }

    let resultcropsid = await ctx.db.EXCUTE("SELECT (SELECT cropname FROM tags ni WHERE n.cropsid=ni.cropsid) AS cropinfo FROM growtime n")
    //获取所有的cropname和potname
    let resultcropall = await ctx.db.EXCUTE("SELECT cropname AS cropall FROM tags")
    let result = await ctx.db.EXCUTE("SELECT n.*, (SELECT potname FROM flowerpot ni WHERE n.potid=ni.potid) AS potinfo FROM growtime n")

    for (let i = 0; i < result.length; i++) {
        Object.assign(result[i], resultcropsid[i]);
        Object.assign(result[i], resultcropall[i]);
    }

    ctx.body = {
        code: 200,
        data: result
    };

});


//编辑item 首先获取该项的内容
router.post('/getsingle', async (ctx, next) => {
    let growid = ctx.request.body.growid;

    let sql = 'SELECT * FROM growtime WHERE growid=?';
    let result = await ctx.db.EXCUTE(sql, [growid]);

    ctx.body = {
        code: 200,
        data: result
    }
})

module.exports = router